#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author:Lijiacai
Email:1050518702@qq.com
===========================================
CopyRight@JackLee.com
===========================================
"""

import datetime
import logging
import multiprocessing
import os
import sys
import json
import requests
import cx_Oracle
import shortuuid
from hashids import Hashids
from elasticsearch_dsl import Search, Q
from elasticsearch import Elasticsearch
from elasticsearch import helpers
import math

cur_dir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append("%s/.." % cur_dir)
import config

sys.path.append("%s/.." % cur_dir)
from res.lijiacai.utils import tool


class StationDistance(tool.RandomString):
    es_cluster = config.es_cluster
    baidu_ak = "eqlcRflrG2vqoncNzlfjbiUqGq3FL6w7"
    station_key = "d9c227c0-a4d2-40ba-b51b-4e479431708a"

    def __init__(self):
        self.es_client = tool.ESClient(cluster=self.es_cluster)

    def gaode2baidu(self, longitude, latitude):
        x_pi = math.pi * 3000.0 / 180.0
        x = longitude
        y = latitude
        z = math.sqrt(x * x + y * y) + 0.00002 * math.sin(y * x_pi)
        theta = math.atan2(y, x) + 0.000003 * math.cos(x * x_pi)
        lng = z * math.cos(theta) + 0.0065
        lat = z * math.sin(theta) + 0.006
        return lng, lat

    def getStations(self):
        headers = {
            "accessKey": self.station_key
        }
        cityIds = [400000, 610000, 650000]
        out = {}
        for city in cityIds:
            mid = {}
            res = requests.get(
                f"{config.station_url}condition.cityId={city}",
                headers=headers).json()
            for one in res.get("cityStations").get("stations"):
                latitude = one.get("latitude", 0)
                longitude = one.get("longitude", 0)
                longitude, latitude = self.gaode2baidu(longitude=one.get("longitude", 0),
                                                       latitude=one.get("latitude", 0))
                stationId = one.get("stationId", 0)
                stationName = one.get("stationName", "")
                mid[stationId] = {"stationName": stationName,
                                  "latitude": latitude,
                                  "longitude": longitude,
                                  "stationId": stationId,
                                  "stationType": "普通站"}
            res = requests.get(
                f"{config.charge_url}condition.cityId={city}",
                headers=headers).json()
            for one in res.get("cityStations").get("stations"):
                latitude = one.get("latitude", 0)
                longitude = one.get("longitude", 0)
                stationId = one.get("stationId", 0)
                stationName = one.get("stationName", "")
                mid[stationId] = {"stationName": stationName,
                                  "latitude": latitude,
                                  "longitude": longitude,
                                  "stationId": stationId,
                                  "stationType": "充电站"}
            out[city] = mid
        return out

    def update(self, index):
        stations = self.getStations()
        out = []
        for k, v in stations.items():
            for k1, v1 in v.items():
                for k2, v2 in v.items():
                    if k1 == k2:
                        continue
                    start_stationId = v1.get("stationId")
                    end_stationId = v2.get("stationId")
                    start_latitude = v1.get("latitude")
                    end_latitude = v2.get("latitude")
                    start_longitude = v1.get("longitude")
                    end_longitude = v2.get("longitude")
                    origins = f"{start_latitude},{start_longitude}"
                    destinations = f"{end_latitude},{end_longitude}"
                    res = requests.get(config.es_cluster[
                                           0] + config.station_distance_dataset + f"/_doc/{start_stationId}_{end_stationId}").json()
                    res = res.get("_source", {})
                    if res.get("start", {}).get("latitude") == start_latitude and \
                            res.get("end", {}).get("latitude") == end_latitude and \
                            res.get("start", {}).get("longitude") == start_longitude and \
                            res.get("end", {}).get("longitude") == end_longitude:
                        pass
                    else:
                        try:
                            url = f"http://api.map.baidu.com/routematrix/v2/driving?output=json&origins={origins}&destinations={destinations}&ak={self.baidu_ak}&tactics=11"
                            res = requests.get(url=url).json()
                        except:
                            continue
                        if res.get("result", []):
                            distance = res.get("result", [])[0].get("distance", {}).get(
                                "value")
                        else:
                            distance = 0
                            logging.debug(res)
                        es_data = {'_op_type': 'index',
                                   '_index': index,
                                   '_type': 'doc',
                                   "_id": f"{start_stationId}_{end_stationId}",
                                   '_source': {
                                       "start": v1,
                                       "end": v2,
                                       "distance": distance,
                                       "cityCode": k
                                   }}
                        out.append(es_data)
                        print(out)
                        return
                    if len(out) == 100:
                        print(1)
                        self.es_client.bulk(actions=out)
                        out = []
        if out:
            # print(json.dumps(out))
            self.es_client.bulk(actions=out)

    def go(self):
        res = self.update(index=config.station_distance_dataset)


if __name__ == '__main__':
    StationDistance().go()
